﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.Web.Mvc.UI;
using TomNet.Web.Mvc;
using System.ComponentModel;
using TomNet.Web.Mvc.Security;
using TomNet.IMSC.Web.Areas.Decoration.Models;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Core.Contracts.Common;

namespace TomNet.IMSC.Web.Areas.Decoration.Controllers
{
    [Description("装修-报备审批")]
    [GlobalAuthorization]
    public class DecorationRunningsController : BaseController
    {
        public IDecorationRunningsContract DecorationRunningsContract { get; set; }
        public IDecorationCompanyContract DecorationCompanyContract { get; set; }
        public IDecorationCompanyStoreContract DecorationCompanyStoreContract { get; set; }
        public IDecorationConsultantContract DecorationConsultantContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IBrokerageRunningsContract BrokerageRunningsContract { get; set; }
        public IDecorationCompanyBrokerageGroupContract DecorationCompanyBrokerageGroupContract { get; set; }
        public IImagesContract ImagesContract { get; set; }//图片


        // GET: Decoration/DecorationRunnings
        [Description("装修-报备审批列表")]
        public ActionResult FilingIndex()
        {
            return View();
        }

        #region 装修-报备审批列表1
        [Description("装修-报备审批列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetList(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("264");



            var query = from d in DecorationRunningsContract.Entities
                        where d.State == 1 && (d.AgentID == model.AgentId || model.AgentId == 0)
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            OriginStaffID = d.OriginStaffID
                        };

            //报备状态1

            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件
            endDate = endDate.AddDays(1);
            query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //渠道人员
            if (OriginStaffID > 0)
            {
                query = query.Where(m => m.OriginStaffID == OriginStaffID);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-带看确认列表")]
        public ActionResult BandSawIndex()
        {
            return View();
        }

        #region 装修-带看确认列表2
        [Description("装修-带看确认列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetListBandSaw(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, int dataType, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("266");


            var query = from d in DecorationRunningsContract.Entities
                        where d.State == 2 && (d.AgentID == model.AgentId || model.AgentId == 0)//审批后状态2            
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            DownPaymentTime = d.DownPaymentTime,
                            OriginStaffID = d.OriginStaffID,
                            SubscribeAmount = d.SubscribeAmount,
                            DownPaymentMoney = d.DownPaymentMoney,
                            FilingAuditingStaffName = (from s in StaffContract.Entities where s.Id == d.FilingAuditingStaffID select s.Name).FirstOrDefault(),
                            ImageCount1 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 1 && !m.IsDeleted select m).Count(),
                            ImageCount2 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 2 && !m.IsDeleted select m).Count(),
                            ImageCount3 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 3 && !m.IsDeleted select m).Count()

                        };
            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件 判断时间类型dataType   0-报备时间，1-报备审核时间
            endDate = endDate.AddDays(1);
            switch (dataType)
            {
                case 0:
                    query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
                    break;
                case 1:
                    query = query.Where(m => m.FilingAuditingTime >= beginDate && m.FilingAuditingTime < endDate);
                    break;
                default:
                    break;
            }

            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //渠道人员
            if (OriginStaffID > 0)
            {
                query = query.Where(m => m.OriginStaffID == OriginStaffID);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-签约确认列表")]
        public ActionResult SubscribeIndex()
        {
            return View();
        }

        #region 装修-签约确认列表（定金-带看完成）4
        [Description("装修-签约列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetListSubscribe(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, int dataType, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("267");
            var query = from d in DecorationRunningsContract.Entities
                        where d.State == 4 && (d.AgentID == model.AgentId || model.AgentId == 0)//带看后状态4            
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            DownPaymentTime = d.DownPaymentTime,
                            OriginStaffID = d.OriginStaffID,
                            SubscribeAmount = d.SubscribeAmount,
                            DownPaymentMoney = d.DownPaymentMoney,
                            ImageCount1 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 1 && !m.IsDeleted select m).Count(),
                            ImageCount2 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 2 && !m.IsDeleted select m).Count(),
                            ImageCount3 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 3 && !m.IsDeleted select m).Count()
                        };
            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件 判断时间类型dataType   0-报备时间，1-报备审核时间,2-带看时间
            endDate = endDate.AddDays(1);
            switch (dataType)
            {
                case 0:
                    query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
                    break;
                case 1:
                    query = query.Where(m => m.FilingAuditingTime >= beginDate && m.FilingAuditingTime < endDate);
                    break;
                case 2:
                    query = query.Where(m => m.BandSawTime >= beginDate && m.BandSawTime < endDate);
                    break;
                default:
                    break;
            }

            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //渠道人员
            if (OriginStaffID > 0)
            {
                query = query.Where(m => m.OriginStaffID == OriginStaffID);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-首期工程款列表")]
        public ActionResult FirstProjectMoneyIndex()
        {
            return View();
        }

        #region 装修-首期工程款列表（定金完成）5
        [Description("装修-首期工程款列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetListFirstProjectMoney(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, int dataType, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("268");
            var query = from d in DecorationRunningsContract.Entities
                        where d.State == 5 && (d.AgentID == model.AgentId || model.AgentId == 0)//签约成功状态5      交完定金  5    
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            DownPaymentTime = d.DownPaymentTime,
                            OriginStaffID = d.OriginStaffID,
                            SubscribeAmount = d.SubscribeAmount,
                            DownPaymentMoney = d.DownPaymentMoney,
                            ImageCount1 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 1 && !m.IsDeleted select m).Count(),
                            ImageCount2 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 2 && !m.IsDeleted select m).Count(),
                            ImageCount3 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 3 && !m.IsDeleted select m).Count()
                        };
            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件 判断时间类型dataType   0-报备时间，1-报备审核时间,2-带看时间，3-签约时间(定金)
            endDate = endDate.AddDays(1);
            switch (dataType)
            {
                case 0:
                    query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
                    break;
                case 1:
                    query = query.Where(m => m.FilingAuditingTime >= beginDate && m.FilingAuditingTime < endDate);
                    break;
                case 2:
                    query = query.Where(m => m.BandSawTime >= beginDate && m.BandSawTime < endDate);
                    break;
                case 3:
                    query = query.Where(m => m.SubscribeTime >= beginDate && m.SubscribeTime < endDate);
                    break;
                default:
                    break;
            }

            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //渠道人员
            if (OriginStaffID > 0)
            {
                query = query.Where(m => m.OriginStaffID == OriginStaffID);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-验收列表")]
        public ActionResult CheckIndex()
        {
            return View();
        }

        #region 装修-验收列表（已付首期工程款）6
        [Description("装修-验收列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetListCheck(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, int dataType, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("269");

            var query = from d in DecorationRunningsContract.Entities
                        where d.State == 6 && (d.AgentID == model.AgentId || model.AgentId == 0)//已付首期工程款 6   
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            DownPaymentTime = d.DownPaymentTime,
                            OriginStaffID = d.OriginStaffID,
                            SubscribeAmount = d.SubscribeAmount,
                            DownPaymentMoney = d.DownPaymentMoney,
                            ImageCount1 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 1 && !m.IsDeleted select m).Count(),
                            ImageCount2 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 2 && !m.IsDeleted select m).Count(),
                            ImageCount3 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 3 && !m.IsDeleted select m).Count()
                        };
            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件 判断时间类型dataType   0-报备时间，1-报备审核时间,2-带看时间，3-签约时间（定金）4-已付首期工程款时间
            endDate = endDate.AddDays(1);
            switch (dataType)
            {
                case 0:
                    query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
                    break;
                case 1:
                    query = query.Where(m => m.FilingAuditingTime >= beginDate && m.FilingAuditingTime < endDate);
                    break;
                case 2:
                    query = query.Where(m => m.BandSawTime >= beginDate && m.BandSawTime < endDate);
                    break;
                case 3:
                    query = query.Where(m => m.SubscribeTime >= beginDate && m.SubscribeTime < endDate);
                    break;
                case 4:
                    query = query.Where(m => m.DownPaymentTime >= beginDate && m.DownPaymentTime < endDate);
                    break;
                default:
                    break;
            }

            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //渠道人员
            if (OriginStaffID > 0)
            {
                query = query.Where(m => m.OriginStaffID == OriginStaffID);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-退单审核列表")]
        public ActionResult ReturnAuditIndex()
        {
            return View();
        }

        #region 装修-退单审核列表
        [Description("装修-退单审核列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetListReturnAudit(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, int dataType, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("271");

            var query = from d in DecorationRunningsContract.Entities
                        where d.ReturnState == 1 && (d.AgentID == model.AgentId || model.AgentId == 0)//退单后所有状态   标记ReturnState由0改为1
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            DownPaymentTime = d.DownPaymentTime,
                            OriginStaffID = d.OriginStaffID,
                            SubscribeAmount = d.SubscribeAmount,
                            DownPaymentMoney = d.DownPaymentMoney,
                            ImageCount1 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 1 && !m.IsDeleted select m).Count(),
                            ImageCount2 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 2 && !m.IsDeleted select m).Count(),
                            ImageCount3 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 3 && !m.IsDeleted select m).Count()
                        };
            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件 判断时间类型dataType   0-报备时间，1-报备审核时间,2-带看时间，3-签约时间，4-首付时间,5-退单申请时间
            endDate = endDate.AddDays(1);
            switch (dataType)
            {
                case 0:
                    query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
                    break;
                case 1:
                    query = query.Where(m => m.FilingAuditingTime >= beginDate && m.FilingAuditingTime < endDate);
                    break;
                case 2:
                    query = query.Where(m => m.BandSawTime >= beginDate && m.BandSawTime < endDate);
                    break;
                case 3:
                    query = query.Where(m => m.SubscribeTime >= beginDate && m.SubscribeTime < endDate);
                    break;
                case 4:
                    query = query.Where(m => m.DownPaymentTime >= beginDate && m.DownPaymentTime < endDate);
                    break;
                case 5:
                    query = query.Where(m => m.ReturnTime >= beginDate && m.ReturnTime < endDate);
                    break;
                default:
                    break;
            }

            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //渠道人员
            if (OriginStaffID > 0)
            {
                query = query.Where(m => m.OriginStaffID == OriginStaffID);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-退单成功列表")]
        public ActionResult ReturnSuccessIndex()
        {
            return View();
        }

        #region 装修-退单完成列表8
        [Description("装修-失败完成列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetListReturnSuccess(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, int dataType, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("267");
            var query = from d in DecorationRunningsContract.Entities
                        where d.State == 8 && (d.AgentID == model.AgentId || model.AgentId == 0)//退单完成 8
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            DownPaymentTime = d.DownPaymentTime,
                            OriginStaffID = d.OriginStaffID,
                            SubscribeAmount = d.SubscribeAmount,
                            DownPaymentMoney = d.DownPaymentMoney,
                            ImageCount1 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 1 && !m.IsDeleted select m).Count(),
                            ImageCount2 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 2 && !m.IsDeleted select m).Count(),
                            ImageCount3 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 3 && !m.IsDeleted select m).Count()
                        };
            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件 判断时间类型dataType   0-报备时间，1-报备审核时间,2-带看时间，3-签约时间，4-退单申请时间,5-退单完成时间
            endDate = endDate.AddDays(1);
            switch (dataType)
            {
                case 0:
                    query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
                    break;
                case 1:
                    query = query.Where(m => m.FilingAuditingTime >= beginDate && m.FilingAuditingTime < endDate);
                    break;
                case 2:
                    query = query.Where(m => m.BandSawTime >= beginDate && m.BandSawTime < endDate);
                    break;
                case 3:
                    query = query.Where(m => m.SubscribeTime >= beginDate && m.SubscribeTime < endDate);
                    break;
                case 4:
                    query = query.Where(m => m.DownPaymentTime >= beginDate && m.DownPaymentTime < endDate);
                    break;
                case 5:
                    query = query.Where(m => m.ReturnTime >= beginDate && m.ReturnTime < endDate);
                    break;
                case 6:
                    query = query.Where(m => m.ReturnAuditingTime >= beginDate && m.ReturnAuditingTime < endDate);
                    break;
                default:
                    break;
            }

            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-验收完成列表")]
        public ActionResult FinishIndex()
        {
            return View();
        }

        #region 装修-验收完成列表7
        [Description("装修-验收完成列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetListFinish(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, int? DecorationCompanyID, int? IntermediaryID, string DecorationConsultantName, int? OriginStaffID, int dataType, decimal beginPrice = 0, decimal endPrice = 0, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //获取权限
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());            
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("267");
            var query = from d in DecorationRunningsContract.Entities
                        where d.State == 7 && (d.AgentID == model.AgentId || model.AgentId == 0)//验收完成7
                        select new DecorationRunningsNew
                        {
                            Id = d.Id,
                            DecorationCompanyID = d.DecorationCompanyID,
                            DecorationCompanyName = d.DecorationCompanyName,
                            IntermediaryID = d.IntermediaryID,
                            IntermediaryName = d.IntermediaryName,
                            UserName = d.UserName,
                            UserPhone = d.UserPhone,
                            CustomerName = d.CustomerName,
                            CustomerPhone = d.CustomerPhone,
                            CustomerAddress = d.CustomerAddress,
                            FilingTime = d.FilingTime,
                            BandSawTime = d.BandSawTime,
                            TotalPrice = d.TotalPrice,
                            Area = d.Area,
                            Remark = d.Remark,
                            OriginStaffName = (from s in StaffContract.Entities where s.Id == d.OriginStaffID select s.Name).FirstOrDefault(),
                            SellStaffID = d.SellStaffID,
                            StarTarget = d.StarTarget,
                            State = d.State,
                            DecorationConsultantName = d.DecorationConsultantName,
                            FilingAuditingTime = d.FilingAuditingTime,
                            SubscribeTime = d.SubscribeTime,
                            DownPaymentTime = d.DownPaymentTime,
                            OriginStaffID = d.OriginStaffID,
                            SubscribeAmount = d.SubscribeAmount,
                            DownPaymentMoney = d.DownPaymentMoney,
                            ImageCount1 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 1 && !m.IsDeleted select m).Count(),
                            ImageCount2 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 2 && !m.IsDeleted select m).Count(),
                            ImageCount3 = (from m in ImagesContract.Entities where m.GroupID == 7 && m.InterfixID == d.Id && m.ImageType == 3 && !m.IsDeleted select m).Count()
                        };
            //判断是否是链接传值
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.DecorationCompanyName.Contains(search));
            }
            //时间条件 判断时间类型dataType   0-报备时间，1-报备审核时间,2-带看时间，3-签约时间（定金）4-已付首期工程款时间 5-验收完成时间
            endDate = endDate.AddDays(1);
            switch (dataType)
            {
                case 0:
                    query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime < endDate);
                    break;
                case 1:
                    query = query.Where(m => m.FilingAuditingTime >= beginDate && m.FilingAuditingTime < endDate);
                    break;
                case 2:
                    query = query.Where(m => m.BandSawTime >= beginDate && m.BandSawTime < endDate);
                    break;
                case 3:
                    query = query.Where(m => m.DownPaymentTime >= beginDate && m.DownPaymentTime < endDate);
                    break;
                case 4:
                    query = query.Where(m => m.SubscribeTime >= beginDate && m.SubscribeTime < endDate);
                    break;
                case 5:
                    query = query.Where(m => m.CompleteTime >= beginDate && m.CompleteTime < endDate);
                    break;
                default:
                    break;
            }

            //装修公司名称id条件
            if (DecorationCompanyID > 0)
            {
                query = query.Where(m => m.DecorationCompanyID == DecorationCompanyID);
            }
            //装修公司门店id条件
            if (IntermediaryID > 0)
            {
                query = query.Where(m => m.IntermediaryID == IntermediaryID);
            }
            //装修顾问
            if (!string.IsNullOrWhiteSpace(DecorationConsultantName) && DecorationConsultantName != "全部")
            {
                query = query.Where(m => m.DecorationConsultantName == DecorationConsultantName);
            }
            //渠道人员
            if (OriginStaffID > 0)
            {
                query = query.Where(m => m.OriginStaffID == OriginStaffID);
            }
            //签约总款起始
            if (beginPrice > 0)
            {
                query = query.Where(m => m.TotalPrice >= beginPrice);
            }
            //签约总款结束
            if (endPrice > 0)
            {
                query = query.Where(m => m.TotalPrice <= endPrice);
            }
            //权限
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationRunningsNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationRunningsNew> gridData = new GridData<DecorationRunningsNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 星标
        [Description("装修-查询星标")]
        public ActionResult SetStarTarget(int id = 0)
        {

            if (id == 0) throw new Exception("参数错误");
            var entity = DecorationRunningsContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该记录");
            ViewBag.entity = entity;
            return View();
        }
        /// <summary>
        /// 设置星标
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Description("设置星标")]
        [AjaxOnly]
        public ActionResult EditSetStarTarget(DecorationRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                var count = DecorationRunningsContract.UpdateDirect(d => entity.Id == d.Id,
                    d => new DecorationRunnings { StarTarget = entity.StarTarget, StarTargetRemark = entity.StarTargetRemark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }
        #endregion

        #region 取消订单        
        /// <summary>
        /// 申请取消订单6
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="remark">取消订单备注</param>
        /// <returns></returns>        
        [Description("取消订单")]
        [AjaxOnly]
        public ActionResult Return(int id, string remark, int state)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var result = new AjaxResult();
            //-----------------------2017年8月8日 修改为取消订单新加字段 取消后改为 1
            var returnstate = 1;
            //如果取消订单所属状态是签约成功则取消到审核 否则直接退到7状态
            //if (state==5)
            //    statenew = 6;
            try
            {
                var count = DecorationRunningsContract.UpdateDirect(d => d.Id == id,
                    d => new DecorationRunnings { ReturnState = returnstate, ReturnTime = DateTime.Now, ReturnStaffID = model.Id, ReturnRemark = remark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "取消订单申请成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "取消订单申请失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-报备审核
        /// <summary>
        /// 报备审核确认2
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="remark">报备审核备注</param>
        /// <returns></returns>
        [Description("装修-报备审核")]
        [HttpPost, AjaxOnly]
        public ActionResult FilingAuditingAffirm(int id, string remark, string flag)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var result = new AjaxResult();
            try
            {
                var state = 2;//默认审核通过状态2
                //选中驳回状态变为3
                if (flag.Equals("2"))
                    state = 3;

                var count = DecorationRunningsContract.UpdateDirect(d => d.Id == id,
                    d => new DecorationRunnings { State = state, FilingAuditingTime = DateTime.Now, FilingAuditingRemark = remark, FilingAuditingStaffID = model.Id });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "报备审核成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "报备审核失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-带看确认
        /// <summary>
        /// 带看确认（已量尺）4
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="remark">带看确认备注</param>
        /// <returns></returns>
        [Description("装修-带看确认")]
        [HttpPost, AjaxOnly]
        public ActionResult BandSawAffirm(int id, string remark)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var result = new AjaxResult();
            try
            {
                var count = DecorationRunningsContract.UpdateDirect(d => d.Id == id,
                    d => new DecorationRunnings { State = 4, BandSawTime = DateTime.Now, BandSawRemark = remark, BandSawStaffID = model.Id });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "带看确认成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "带看确认失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-退单审核
        /// <summary>
        /// 报备审核确认
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="remark">退单审核备注</param>
        /// <returns></returns>
        [Description("装修-退单审核")]
        [HttpPost, AjaxOnly]
        public ActionResult FilingAuditingAudit(int id, string remark, string flag)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var result = new AjaxResult();
            try
            {
                var count = -1;
                //flag 1-同意通过 ， 2- 不同意
                if (flag.Equals("1"))//同意退单审核到ReturnState=2状态State = 8
                {
                    count = DecorationRunningsContract.UpdateDirect(d => d.Id == id,
                d => new DecorationRunnings { State = 8, ReturnAuditingTime = DateTime.Now, ReturnAuditingRemark = remark, ReturnStaffID = model.Id, ReturnState = 2 });
                }
                else if (flag.Equals("2"))//不同意退单则 State不变 ReturnState=0
                {
                    count = DecorationRunningsContract.UpdateDirect(d => d.Id == id, d => new DecorationRunnings { ReturnState = 0 });
                }
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "退单审核成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "退单审核失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修列表参数
        [Description("装修-装修列表参数")]
        [HttpPost, AjaxOnly]
        public ActionResult DictionaryLoad()
        {
            var result = new AjaxResult();

            var DecorationCompany = DecorationCompanyContract.Entities.Where(m => !m.IsDeleted).OrderBy(m => m.Id).Select(m => new
            {//装修公司
                id = m.Id,
                text = m.Name
            }).ToList();
            var DecorationCompanyStore = DecorationCompanyStoreContract.Entities.Where(m => !m.IsDeleted).OrderBy(m => m.Id).Select(m => new
            {//门店
                id = m.Id,
                text = m.Name
            }).ToList();
            var DecorationConsultant = DecorationConsultantContract.Entities.Where(m => !m.IsDeleted).OrderBy(m => m.Id).Select(m => new
            {//装修顾问
                id = m.Id,
                text = m.Name
            }).ToList();
            var Staff = StaffContract.Entities.Where(m => !m.IsDeleted).OrderBy(m => m.Id).Select(m => new
            {//渠道人员
                id = m.Id,
                text = m.Name
            }).ToList();
            result.Data = new
            {
                DecorationCompany = DecorationCompany,
                DecorationCompanyStore = DecorationCompanyStore,
                DecorationConsultant = DecorationConsultant,
                Staff = Staff
            };
            result.Type = AjaxResultType.Success;
            return JsonEx(result);
        }
        #endregion


        #region 操作员明细
        [Description("装修-操作员明细")]
        public ActionResult OperatorDetails(int Id)
        {
            var query = from r in DecorationRunningsContract.Entities
                        where r.Id == Id
                        select new
                        {
                            FilingAuditingStaffName = (from s in StaffContract.Entities where s.Id == r.FilingAuditingStaffID select s.Name).FirstOrDefault(),
                            BandSawStaffName = (from s in StaffContract.Entities where s.Id == r.BandSawStaffID select s.Name).FirstOrDefault(),
                            SubscribeStaffName = (from s in StaffContract.Entities where s.Id == r.SubscribeStaffID select s.Name).FirstOrDefault(),
                            ReturnStaffIName = (from s in StaffContract.Entities where s.Id == r.ReturnStaffID select s.Name).FirstOrDefault(),
                            ReturnAuditingStaffName = (from s in StaffContract.Entities where s.Id == r.ReturnAuditingStaffID select s.Name).FirstOrDefault()
                        };
            Dictionary<string, string> op = new Dictionary<string, string>();

            foreach (var item in query)
            {
                op.Add("报备审核操作员", item.FilingAuditingStaffName);
                op.Add("带看确认操作员", item.BandSawStaffName);
                op.Add("签约确认操作员", item.SubscribeStaffName);
                op.Add("退单审核操作员", item.ReturnStaffIName);
                op.Add("退单确认操作员", item.ReturnAuditingStaffName);
            }
            ViewData["operator"] = op;
            return View();
        }
        #endregion

        [Description("装修-签约操作")]
        public ActionResult SubscribeAffirm()
        {
            return View();
        }
        #region 装修-签约
        /// <summary>
        /// 签约5
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="remark">签约（定金操作）</param>
        /// <returns></returns>
        [Description("装修-签约")]
        [HttpPost, AjaxOnly]
        public ActionResult SubscribeAsync(DecorationRunnings entity)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var result = new AjaxResult();
            try
            {
                var count = DecorationRunningsContract.UpdateDirect(d => d.Id == entity.Id,
                    d => new DecorationRunnings { State = 5, SubscribeTime = entity.SubscribeTime, SubscribeStaffID = model.Id, DecorationCompanyBrokerageGroupID = entity.DecorationCompanyBrokerageGroupID, TotalPrice = entity.TotalPrice, Area = entity.Area, SubscribeReamrk = entity.SubscribeReamrk, SubscribeAmount = entity.SubscribeAmount });
                if (count > 0)
                {
                    BrokerageRunningsContract.InitBrokerage(4, entity.Id);
                    BrokerageRunningsContract.InitSalary(4, entity.Id);
                    result.Type = AjaxResultType.Success;
                    result.Content = "签约成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "签约失败";
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        public ActionResult FirstProjectMoneyAffirm()
        {
            return View();
        }

        #region 装修-首期工程款确认
        /// <summary>
        /// 首期工程款6
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="remark">首期工程款</param>
        /// <returns></returns>
        [Description("装修-首期工程款确认")]
        [HttpPost, AjaxOnly]
        public ActionResult FirstProjectMoneyOperate(DecorationRunnings entity)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var result = new AjaxResult();
            try
            {
                var count = DecorationRunningsContract.UpdateDirect(d => d.Id == entity.Id,
                    d => new DecorationRunnings { State = 6, DownPaymentTime = entity.DownPaymentTime, DownPaymentStaffID = model.Id, DownPaymentRemark = entity.DownPaymentRemark, DownPaymentMoney = entity.DownPaymentMoney });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "首期工程款确认成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "首期工程款确认失败";
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-验收
        /// <summary>
        /// 验收7
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="remark">验收</param>
        /// <returns></returns>
        [Description("装修-验收")]
        [HttpPost, AjaxOnly]
        public ActionResult CheckOperate(int id, string remark)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var result = new AjaxResult();
            try
            {
                var count = DecorationRunningsContract.UpdateDirect(d => d.Id == id,
                    d => new DecorationRunnings { State = 7, CompleteTime = DateTime.Now, DownPaymentStaffID = model.Id, CompleteRemark = remark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "验收成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "验收失败";
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修公司佣金分组
        [Description("装修-获取装修公司佣金分组")]
        [HttpPost, AjaxOnly]
        public ActionResult GetBrokerageGroup(int DecorationCompanyId)
        {
            var result = new AjaxResult();

            var DecorationCompanyBrokerageGroup = DecorationCompanyBrokerageGroupContract.Entities.Where(m => m.DecorationCompanyID == DecorationCompanyId).OrderBy(m => m.Id).Select(m => new
            {//装修公司
                id = m.PercentageType,
                name = m.Name
            }).ToList();
            result.Data = new
            {
                DecorationCompanyBrokerageGroup = DecorationCompanyBrokerageGroup
            };
            result.Type = AjaxResultType.Success;
            return JsonEx(result);
        }
        #endregion

        #region 用于装修公司、门店、顾问下拉列表联动查询
        [Description("装修-下拉列表联动查询")]
        [AjaxOnly]
        public ActionResult BlocokLoad(int? companyid, int? storeid)
        {
            var result = new AjaxResult();

            var DecorationCompanyStore = DecorationCompanyStoreContract.Entities.Where(m => !m.IsDeleted && m.DecorationCompanyID == companyid).OrderBy(m => m.Id).Select(m => new
            {//门店
                id = m.Id,
                text = m.Name
            }).ToList();


            var DecorationConsultant = DecorationConsultantContract.Entities.Where(m => !m.IsDeleted && m.DecorationCompanyStoreID == storeid).OrderBy(m => m.Id).Select(m => new
            {//装修顾问
                id = m.Id,
                text = m.Name
            }).ToList();

            result.Data = new
            {
                DecorationCompanyStore = DecorationCompanyStore,
                DecorationConsultant = DecorationConsultant
            };
            result.Type = AjaxResultType.Success;
            return JsonEx(result);
        }
        #endregion


        [Description("客户姓名-修改")]
        //[GlobalAuthorization]
        public ActionResult CustomerNameEdit(int id)
        {
            var entity = DecorationRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("客户姓名-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult CustomerNameEditAsync(DecorationRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = DecorationRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { CustomerName = entity.CustomerName });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("客户电话-修改")]
        //[GlobalAuthorization]
        public ActionResult CustomerPhoneEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = DecorationRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("客户电话-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult CustomerPhoneEditAsync(DecorationRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = DecorationRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { CustomerPhone = entity.CustomerPhone });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("面积-修改")]
        //[GlobalAuthorization]
        public ActionResult AreaEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = DecorationRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("面积-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult AreaEditAsync(DecorationRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = DecorationRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { Area = entity.Area });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("地址-修改")]
        //[GlobalAuthorization]
        public ActionResult AddressEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = DecorationRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("地址-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult AddressEditAsync(DecorationRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = DecorationRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { CustomerAddress = entity.CustomerAddress });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }


        [Description("地址-修改")]
        //[GlobalAuthorization]
        public ActionResult RemarkEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = DecorationRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }
        [Description("地址-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult RemarkEditAsync(DecorationRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = DecorationRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new DecorationRunnings { Remark = entity.Remark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
    }
}